package cn.smdq.ch.upms.admin.config.listener;

import cn.smdq.ch.common.constant.CommonConstants;
import cn.smdq.ch.common.dto.RoutesDTO;
import cn.smdq.ch.upms.admin.base.entity.Routes;
import cn.smdq.ch.upms.admin.base.service.IRoutesService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty;

/**
 * @author shuimodanqing
 * create at:  2019/1/24  2:59 PM
 * @description 动态路由监听器
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class DynamicRouteListener {

    private RedisTemplate redisTemplate;

    private IRoutesService routesService;

    public DynamicRouteListener(RedisTemplate redisTemplate, IRoutesService routesService) {
        this.redisTemplate = redisTemplate;
        this.routesService = routesService;
    }

    @PostConstruct
    public void init() {
        log.info("初始化路由配置......");
        List<Routes> routeList = routesService.list(Wrappers.<Routes>lambdaQuery().eq(Routes::getDelFlag, CommonConstants.STATUS_NORMAL));
        if (isNotEmpty(routeList)) {
            List<RoutesDTO> routesDTOList = routeList.stream().map(target -> {
                RoutesDTO routesDTO = new RoutesDTO();
                BeanUtils.copyProperties(target, routesDTO);
                return routesDTO;
            }).collect(Collectors.toList());
            System.out.println("路由信息: " + routesDTOList.get(0).getPath());
            redisTemplate.opsForValue().set(CommonConstants.GATEWAY_ROUTE_KEY, routesDTOList);
            log.info("redis中更新{}条路由信息", routeList.size());
        }
        log.info("初始化路由信息完成......");
    }
}
